package com.bb.blog.code.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkWatcher implements Watcher {
    private static final String path = "/user1nam112113e11";
    private CountDownLatch countDownLatch;
    private ZooKeeper zk;
    private Stat stat;


    public static void main(String[] args) throws InterruptedException {
        ZkWatcher newInstance = new ZkWatcher();

    }

    public ZkWatcher() {
        try {
            stat = new Stat();
            countDownLatch = new CountDownLatch(1);
            zk = new ZooKeeper("127.0.0.1:2181", 20000, this);

            countDownLatch.await();

            List<String> children = zk.getChildren("/", this);
            for (String child : children) {
                zk.delete("/" + child,-1);
            }


            Thread.sleep(10000);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        if (Event.KeeperState.SyncConnected.equals(watchedEvent.getState())) {
            if (Event.EventType.None.equals(watchedEvent.getType()) && null == watchedEvent.getPath()) {
                System.out.println("链接成功");
                countDownLatch.countDown();
            }


        }
        System.out.println(watchedEvent.toString());
    }


}
